<?php

namespace app\models;

use app\components\exceptions\InvalidRequestException;
use Yii;
use yii\db\Query;

/**
 * This is the model class for table "shop_category".
 *
 * @property int $id
 * @property string $name 分类名称
 * @property int $parent_id 父级id
 * @property int $created
 * @property int $updated
 * @property int $is_dir 是否为目录，1=是，2=否
 * @property string $path 父级路径
 * @property int $level 层级
 */
class ShopCategory extends \yii\db\ActiveRecord
{
    use Common;
    const IS_DIR_YES = 1;
    const IS_DIR_NO = 2;

    private $scriptTime;//脚本开始时间

    public function __construct(array $config = [])
    {
        parent::__construct($config);
        $this->scriptTime = time();
    }

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%shop_category}}';

    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            ['id', 'required', 'on' => [SCENARIO_UPDATE]],
            [
                'name', 'unique',
                'filter' => function (Query $query) {
                    $this->id && $query->andWhere(['!=', 'id', $this->id]);
                    return $query;
                }, 'message' => '分类名称已存在', 'on' => [SCENARIO_STORE, SCENARIO_UPDATE]
            ],
            [['name', 'parent_id', 'is_dir'], 'required', 'message' => '{attribute}不能为空', 'on' => [SCENARIO_STORE]],
            ['is_dir', 'in', 'range' => [1, 2], 'message' => '{attribute}值不在合法范围内', 'on' => [SCENARIO_STORE, SCENARIO_UPDATE]]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'name' => '分类名称',
            'parent_id' => '父级ID',
            'created' => '创建时间',
            'updated' => '更新时间',
            'is_dir' => '目录',
            'path' => '路径',
            'level' => '层级',
        ];
    }

    /**
     * 设置path属性和level属性
     */
    public function setPathAndLevel()
    {
        if (!$this->parent_id) {
            //顶级分类
            $this->level = 0;
            $this->path = '-';
        } else {
            //子分类
            $this->level = $this->parent->level + 1;
            $this->path .= $this->parent->path . $this->parent_id . '-';
        }

    }

    public function getParent()
    {
        return $this->hasOne(ShopCategory::class, ['id' => 'parent_id']);
    }

    public function getChildren()
    {
        return $this->hasMany(ShopCategory::class, ['parent_id' => 'id']);
    }

    /**
     * 获取所有的父级id
     * @return array
     */
    public function getParentIds()
    {
        return array_filter(explode('-', trim($this->path, '-')));
    }

    /**
     * 获取所有的祖先类目拼按层级分类
     */
    public function getAncestors()
    {
        return self::find()
            ->where(['in', 'id', $this->parentIds])
            ->orderBy('level')
            ->all();
    }


    /**
     * 新增记录
     * @throws
     */
    public function saveCategory($data)
    {
        //装载数据
        $this->loadData($data, SCENARIO_STORE);

        $this->setPathAndLevel();
        $this->updated = $this->scriptTime;
        $this->created = $this->updated;

        if (!$this->save()) {
            throw new InvalidRequestException(1011);
        }


    }

    /**
     * 是否为目录
     */
    public function getIsDirText()
    {
        if ($this->is_dir == self::IS_DIR_YES) {
            return '是';
        } else {
            return '否';
        }
    }


    /**
     * 更新操作
     * @param $data
     * @throws
     */
    public function updateCategory($data)
    {
        //装载数据
        $this->loadData($data, SCENARIO_UPDATE);

        if (!$category = self::findOne($this->id)) throw new InvalidRequestException(1012);


        if ($category->parent_id != $this->parent_id) {
            //重新计算父级
            $this->setPathAndLevel();

            $category->parent_id = $this->parent_id;

            $category->level = $this->parent_id;
        }

        $category->is_dir = $this->is_dir;

        //数据更新时间
        $category->updated = $this->scriptTime;

        if (!$category->update()) throw new InvalidRequestException(1013);

    }


}
